package Midium;

import java.util.Stack;

//43.字符串相乘
public class Solution43 {
    public String multiply(String num1, String num2) {
        if(num1.equals("0")||num2.equals("0"))
            return "0";
        //num1去乘以num2的每一位，最后加起来，因此一共计算了num2.length个式子后再相加
        String[] strlist = new String[num2.length()];
        for(int i = 0 ,j=num2.length()-1; i < num2.length() ; i++,j--){
            strlist[i] = multy(num1,num2.charAt(j)-48,i);
        }
        return addNSum(strlist);

    }

    //N数相加
    public String addNSum(String[] strlist) {
        String res = "0";
        for(String str : strlist){
            res=addSum(res,str);
        }
        return res;
    }

    //两数相加
    public String addSum(String sa, String sb) {
        int jinwei = 0;
        //两数中较小的数的长度
        StringBuffer res = new StringBuffer();
        Stack stack = new Stack<>();
        int i, j;
        for (i = sa.length() - 1, j = sb.length() - 1; i >= 0 && j >= 0; i--, j--) {
            char _a = sa.charAt(i);
            char _b = sb.charAt(j);
            int a = _a - 48;
            int b = _b - 48;
            int sum = a + b;
            char c = (char) ((sum+ jinwei) % 10 + 48 );
            jinwei = (sum+jinwei) / 10;
            stack.add(c);
        }
        while (i >= 0) {
            char _a = sa.charAt(i--);
            int a = _a - 48;
            int sum = a + jinwei;
            char c = (char) (sum % 10 + 48);
            jinwei = sum / 10;
            stack.add(c);
        }
        while (j >= 0) {
            char _b = sb.charAt(j--);
            int b = _b - 48;
            int sum = b + jinwei;
            char c = (char) (sum % 10 + 48);
            jinwei = sum / 10;
            stack.add(c);
        }
        if (jinwei != 0)
            stack.add((char) (jinwei + 48));
        while (!stack.empty()) {
            res.append(stack.pop());
        }
        return new String(res);

    }


    //str*a*tenCount
    public String multy(String str, int b, int tenCount) {
        int jinwei = 0;
        Stack stack = new Stack<>();
        for (int i = str.length() - 1; i >= 0; i--) {
            char _a = str.charAt(i);
            int a = _a - 48;
            int product = a * b;
            char c = (char) ((product+ jinwei) % 10 + 48 );
            jinwei = (product+jinwei) / 10;
            stack.add(c);
        }
        if (jinwei != 0) {
            stack.add((char) (jinwei + 48));
        }
        StringBuffer res = new StringBuffer();
        while (!stack.empty()) {
            res.append(stack.pop());
        }
        while (tenCount != 0) {
            res.append('0');
            tenCount--;
        }
        return new String(res);
    }

    public static void main(String[] args) {
        Solution43 s43 = new Solution43();
        System.out.println(s43.multiply("123456789","321"));
    }
}
